<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./vue.js"></script>
</head>

<body>
    <!-- 定义挂载点 -->
    <div id="app">
        <h3>name : {{name}}</h3>
        <h3>age : {{age}}</h3>

        <table width="500" border="1">
            <thead>
                <tr>
                    <th width="40%">姓名</th>
                    <th>成绩</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="item in students" :key="item.id">
                    <td>{{item.name}}</td>
                    <td><input type="text" v-model.number="item.score"></td>
                </tr>
                <tr>
                    <td>平均分</td>
                    <td>{{avaScore|filterFixed}}</td>
                </tr>
            </tbody>
        </table>

        //方法-调用多少次就会执行多少次
        <button @click="getAvaScore">按钮</button>
        {{ava}}

        <!-- 计算属性：具有缓存，数据发生了变化才会重新调用计算 -->
        {{avaScore}}
        {{avaScore}}
        {{avaScore}}
    </div>

    <script>
        //定义全局过滤器
        Vue.filter("filterFixed", (n) => {
            return n.toFixed(2)
        })
        new Vue({
            //挂载点
            el: "#app",
            //数据
            data: {
                name: "孙尚香",
                students: [
                    { id: 1, name: "妲己", score: 90 },
                    { id: 2, name: "王昭君", score: 80 },
                    { id: 3, name: "貂蝉", score: 70 }
                ],
                ava:0
            },
            //方法
            methods: {
                getAvaScore() {
                    let sum = 0; //存储和
                    this.students.forEach(value => {
                        sum += value.score;
                    });
                    this.ava = sum / this.students.length;
                    console.log("方法");
                }
            },

            //计算属性：需要通过计算后得到的值，就会使用计算属性
            //依赖数据，如果数据发生变化，会重新计算
            computed: {
                age() {
                    return 20
                },
                avaScore() {
                    console.log("计算属性");
                    let sum = 0; //存储和
                    this.students.forEach(value => {
                        sum += value.score;
                    });
                    return sum / this.students.length
                }

            }
        })
    </script>
</body>

</html>